#-*- coding:UTF-8 -*-
from django.shortcuts import render,HttpResponseRedirect,HttpResponse
from application.models import projectAndMachineInfo,bugs,uploadImg,userInfo,projectInfo,projectAndWorkerRelations,caseInfo,projectAndCaseRelations,notebookAndCellPhoneAndPadInfos,projectAndMachineInfo
from django.db import transaction
import json,sys,os
from dqms import settings

def projectManagePage(request):
    context = {}
    projects = projectInfo.objects.all();
    context['projects'] = projects;
    return render(request, "admin/projectManagePage.html",context);


@transaction.atomic
def addProject(request):
    projectName = request.POST.get('projectName')
    projectRemark = request.POST.get('projectRemark')
    cases = caseInfo.objects.all();
    try:
        with transaction.atomic():
            projectInfo(projectName=projectName,projectRemark=projectRemark).save()
            newPro = projectInfo.objects.get(projectName=projectName);
            for case in cases:
                prRelations = projectAndCaseRelations();
                prRelations.projectId=newPro.id
                prRelations.caseId=case.id
                prRelations.status='1'
                prRelations.save();
    except Exception:
        return HttpResponseRedirect('/projectManagePage/');
    return HttpResponseRedirect('/projectManagePage/');


def main(request):
    return render(request,"frame.html");


def menu(request):
    return render(request,"menu.html");


def changeProjectInfo(request):
    projectName = request.POST.get('projectName');
    projectId = request.POST.get('projectId');
    projectStatus = request.POST.get('projectStatus');
    result = 1;
    try:
        project = projectInfo.objects.get(id=projectId);
        project.projectName = projectName;
        project.status = projectStatus;
        project.save();
    except Exception:
        result = 0;
    return HttpResponse(result);



def allocateProjectToWorkers(request):
    projectId = request.POST.get('projectIdData');
    projects = projectInfo.objects.filter(id=projectId);
    users = userInfo.objects.filter(status='1');
    projectWorkers = projectAndWorkerRelations.objects.filter(projectId=projectId);
    relations = []
    for user in users:
        flag = False;
        for projectWorker in projectWorkers:
            if projectWorker.userId == user.id:
                flag = True;
                break;
        relation = {}
        relation['user'] = user;
        if flag is True:
            relation['status'] = 1;
        else:
            relation['status'] = 0;
        relations.append(relation)
    context = {}
    context['projects'] = projects;
    context['relations'] = relations;
    return render(request,'admin/allocateProjectToWorkersPage.html',context);



def doAllocateProject(request):
    projectId = request.POST.get('projectId');
    userId = request.POST.get('userId');
    status = request.POST.get('status');
    result = 1;
    try:
        if status == '1':
            projectAndWorkerRelations(projectId=projectId,userId=userId).save();
        else:
            projectAndWorkerRelations.objects.filter(projectId=projectId,userId=userId).delete()
    except Exception:
        result = 0;
    return HttpResponse(result);


def addCaseToProjectPage(request):
    caseInfos = caseInfo.objects.all();
    projectId = request.POST.get('projectIdData');
    projectInfos = projectInfo.objects.get(id=projectId);
    context = {}

    context['projectInfo'] = projectInfos;
    pcrs = projectAndCaseRelations.objects.filter(projectId=projectId);
    projectListAndStatus = [];
    for ci in caseInfos:
        flag = False;
        for pcr in pcrs:
            if int(pcr.caseId) == ci.id and pcr.status == '1':
                flag = True;
                break;
        ps = {}
        ps['caseInfo'] = ci;
        if flag is True:
            ps['status'] = 1;
        else:
            ps['status'] = 0;
        projectListAndStatus.append(ps)
        context['caseInfos'] = projectListAndStatus;
    return render(request,'admin/addCaseToProjectPage.html',context);


def deleteProject(request):
    projectId = request.POST.get('projectId');
    result = 1;
    try:
        projectInfo(id=projectId).delete();
        projectAndCaseRelations.objects.filter(projectId=projectId).delete();
        projectAndWorkerRelations.objects.filter(projectId=projectId).delete();
    except Exception:
        print(Exception);
        result = 0;
    return HttpResponse(result);

def todoCaseAndProjectRelations(request):
    type = request.POST.get('type');
    projectId = request.POST.get('projectId');
    caseId = request.POST.get('caseId');
    result = 1;
    #取消操作
    try:
        relation = projectAndCaseRelations.objects.get(projectId=projectId,caseId=caseId);
        if type=='0':
            relation.status = '0';
            relation.save();
        if type=='1':
            relation.status = '1';
            relation.save();
        if type=='2':
            projectAndCaseRelations.objects.get(projectId=projectId,caseId=caseId).delete()
            caseInfo.objects.get(id=caseId).delete()
    except Exception:
        result = 0;
    return HttpResponse(result);

def notebookAndCellPhoneAndPadInfosPage(request):
    machines = notebookAndCellPhoneAndPadInfos.objects.all();
    context = {}
    context['infos'] = machines;
    return render(request,"admin/notebookAndCellPhoneAndPadInfosPage.html",context);

def addMachineInfo(request):
    result = 1;
    name = request.POST.get('name');
    info = request.POST.get('info');
    try:
        notebookAndCellPhoneAndPadInfos(name=name,mainInfo=info).save();
    except Exception:
        print(Exception)
        result = 0;
    return HttpResponse(result)


def delMachineInfo(request):
    result = 1;
    ids = request.POST.get('ids');
    idl = str.split(ids,'-');
    try:
        notebookAndCellPhoneAndPadInfos.objects.filter(id__in=idl).delete();
    except Exception:
        result = 0;
    return HttpResponse(result);

def projectAndMachinesRelationsPage(request):
    projectId = request.GET.get('projectId');
    stage = request.GET.get('stage');
    machinesAndStatusList = []
    context = {}
    pms = projectAndMachineInfo.objects.filter(projectId = projectId,stage = stage);
    projects = projectInfo.objects.all();
    machines = notebookAndCellPhoneAndPadInfos.objects.all();
    for machine in machines:
        machinesAndStatus = {}
        flag = False;
        machinesAndStatus['machine'] = machine;
        for pm in pms:
            if int(pm.machineId) == machine.id:
                flag = True;
                break;
        if flag:
            machinesAndStatus['status'] = 1;
            worker = userInfo.objects.get(id=pm.userId);
            machinesAndStatus['tester'] = worker.showName;
        else:
            machinesAndStatus['status'] = 0;
            machinesAndStatus['tester'] = 'N/A';
        machinesAndStatusList.append(machinesAndStatus)
    context['projectSelect'] = int(projectId);
    context['stage'] = stage;
    context['machineAndStatus'] = machinesAndStatusList;
    context['projects'] = projects;
    return render(request,'admin/projectAndMachinesRelationsPage.html',context)

def getMachineToTestAndPn(request):
    projectId = request.POST.get('projectId');
    machineId = request.POST.get('machineId');
    stage = request.POST.get('stage');
    userId = request.session.get('userId') ;
    pn = request.POST.get('pn');
    result = 1;
    try:
        projectAndMachineInfo(pn=pn,projectId=projectId,userId=userId,stage=stage,machineId=machineId).save()
    except Exception:
        result = 0;
    return HttpResponse(result)

def uploadFile(request):
    result = {};
    try:
        file_obj = request.FILES.get('file');
        fileName = file_obj.name;
        fileNameImg = 'img/'+fileName;
        projectId = request.POST.get('projectId');
        caseTitleId = request.POST.get('caseTitleId');
        caseDetailId = request.POST.get('caseDetailId');
        userId = request.session.get('userId')
        files = uploadImg.objects.filter(img=fileNameImg);
        with transaction.atomic():
            if files.count()>0:
                result['data'] = 2;
                return HttpResponse(json.dumps(result));
            if file_obj is not None:
                uploadImg(img = file_obj,imgName=fileName).save();
                imgfile = uploadImg.objects.filter(img=fileNameImg)[0];
                result['data'] = 1;
                result['fileName'] = fileName;
                result['uploadId'] = imgfile.id;
                bugz = bugs.objects.filter(projectId=int(projectId),caseDetailId=int(caseDetailId),caseId=int(caseTitleId),userId=int(userId));
                imgIds = str(imgfile.id);
                bug = bugs();
                if bugz.count() == 1:
                    bug = bugz[0];
                    if bug.imgId is not None:
                        imgIds = str(imgfile.id)+','+bug.imgId;
                    bug.imgId = imgIds;
                    bug.save();
                if bugz.count() == 0:
                    bugNew = bugs();
                    bugNew.projectId=int(projectId)
                    bugNew.caseDetailId=int(caseDetailId)
                    bugNew.caseId=int(caseTitleId)
                    bugNew.userId=int(userId)
                    bugNew.imgId = imgIds
                    bugNew.save();
                    bug = bugs.objects.filter(projectId=int(projectId), caseDetailId=int(caseDetailId),
                                               caseId=int(caseTitleId), userId=int(userId))[0];
                imgfile.bugId = bug.id;
                imgfile.save();
                return HttpResponse(json.dumps(result));
            else:
                result['data'] = 0;
    except Exception:
        print(sys.exc_info())
        result['data'] = 0;
    return HttpResponse(result);


def deleteImg(request):
    result = 1;
    try:
        imgId = request.POST.get('imgId');
        uploadFile = uploadImg.objects.get(id=imgId);
        bugId = uploadFile.bugId;
        fileName = uploadFile.img;
        bug = bugs.objects.get(id=bugId);
        imgIds = bug.imgId.split(',');
        newIds = '0';
        for id in imgIds:
            if id != imgId:
                newIds = id+','+newIds
        with transaction.atomic():
            bug.imgId = newIds;
            bug.save();
            uploadFile.delete();
            os.remove(os.path.join(settings.MEDIA_ROOT,fileName.name))
    except Exception:
        print(sys.exc_info())
        result = 0;
    return HttpResponse(result);


def submitFailReason(request):
    result = 1;
    projectId = request.POST.get('projectId');
    caseDetailId = request.POST.get('caseDetailId');
    caseTitleId = request.POST.get('caseTitleId');
    userId = request.session.get('userId');
    stage = request.POST.get('stage');
    machineId = request.POST.get('machineId');
    try:
        state = request.POST.get('state');
        reason = request.POST.get('failReason');
        reason = str.replace(reason,'\n','<br>');
        bugTitle = request.POST.get('bugTitle');
        bug = bugs.objects.filter(projectId=int(projectId),caseId=int(caseTitleId),caseDetailId=int(caseDetailId),userId=int(userId),stage=stage,machineId=machineId);
        if bug.count() > 0:
            abug = bug[0];
            abug.comment = reason;
            abug.state = state;
            abug.title = bugTitle;
            abug.save();
        else:
            bugNew = bugs();
            bugNew.projectId = int(projectId)
            bugNew.caseDetailId = int(caseDetailId)
            bugNew.caseId = int(caseTitleId)
            bugNew.userId = int(userId)
            bugNew.comment = reason;
            bugNew.state = state;
            bugNew.title = bugTitle;
            bugNew.stage = stage;
            bugNew.machineId = machineId;
            bugNew.save();
    except Exception:
        print(sys.exc_info())
        result = 0;
    return HttpResponse(result);

def showImage(request):
    imgSrc = request.GET.get('imgSrc');
    context = {}
    context['src'] = imgSrc;
    return render(request,"img/show.html",context);


def getMachineToTest(request):
    projectId = request.POST.get('projectId');
    stage = request.POST.get('stage');
    userId = request.session.get('userId');
    machineIds = projectAndMachineInfo.objects.filter(projectId=projectId,userId=userId,stage=stage).values("machineId");
    ids = [];
    for id in machineIds:
        ids.append(int(id['machineId']));
    machines = notebookAndCellPhoneAndPadInfos.objects.filter(id__in=ids).values('id','name');
    listM = list(machines);
    result = json.dumps(listM);
    return HttpResponse(result);